package com.meis.widget.radius;

import com.meis.widget.radius.delegate.RadiusTextViewDelegate;
import cs.help.tool.Log;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.app.Context;

/**
 * Created: AriesHoo on AriesHoo on 2017-02-10 14:24
 * E-Mail: AriesHoo@126.com
 * Function: 用于需要圆角矩形框背景的TextView的情况,减少直接使用TextView时引入的shape资源文件
 * Description:
 * 1、2018-2-5 14:27:16 初始化TextView的 RadiusTextViewDelegate
 */
public class RadiusTextView extends Text implements Component.EstimateSizeListener {
    private RadiusTextViewDelegate delegate;

    public RadiusTextView(Context context) {
        this(context, null);
    }

    public RadiusTextView(Context context, AttrSet attrs) {
        this(context, attrs, null);
    }

    public RadiusTextView(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        delegate = new RadiusTextViewDelegate(this, context, attrs);
        setEstimateSizeListener(this::onEstimateSize);
        //setTouchEventListener(this::onTouchEvent);
         init();
    }


    private void init(){
        if (delegate == null) {
            return ;
        }
        getContext().getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                Log.i("mzl", "RadiusTextView init " + getEstimatedHeight() + delegate.getRadiusHalfHeightEnable() + getText());
                if (delegate.getRadiusHalfHeightEnable()) {
                    delegate.setRadius(getEstimatedHeight() / (float) 2);
                }
                delegate.init();
            }
        }, 10);
    }


    /**
     * 获取代理类用于Java代码控制shape属性
     *
     * @return RadiusTextViewDelegate
     */
    public RadiusTextViewDelegate getDelegate() {
        return delegate;
    }


    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
        if (delegate != null) {
            delegate.setSelected(selected);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (delegate != null) {
            delegate.init();
        }
    }

    @Override
    public void setPressState(boolean pressState) {
        super.setPressState(pressState);
        if (delegate != null) {
            delegate.init();
        }
    }

    @Override
    public boolean onEstimateSize(int i, int i1) {
        if (delegate == null) {
            return true;
        }
        setEstimatedSize(EstimateSpec.getSize(i), EstimateSpec.getSize(i1));
        if (delegate.getWidthHeightEqualEnable() && getEstimatedWidth() > 0 && getEstimatedHeight() > 0) {
            int max = Math.max(getEstimatedWidth(), getEstimatedHeight());
            int measureSpec = EstimateSpec.getSizeWithMode(max, EstimateSpec.PRECISE);
            super.estimateSize(measureSpec, measureSpec);
        }
        return false;
    }
}